package edu.guet.cn.blogbasics.service.impl;

import edu.guet.cn.blogbasics.entity.Users;
import edu.guet.cn.blogbasics.mapper.UserRoleMapper;
import edu.guet.cn.blogbasics.mapper.UsersMapper;
import edu.guet.cn.blogbasics.service.UsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hejianding
 * @since 2021-03-30
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService {

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    public Users login(Users users) {
        Users users1 = usersMapper.login(users);
        if (users1 != null) {
            return users1;
        }
        throw new RuntimeException("认证失败！");
    }

    @Override
    public Users findByName(String userName) {
        return usersMapper.findByName(userName);
    }

    @Override
    public List<String> getRolesByUserName(String userName) {
        return usersMapper.getRolesByUserName(userName);
    }

    /*
    注册一个注册成功后的users到controller层
     */
    @Override
    public Users insertUsers(Users users) {
        Users users1= new Users();
        users1.setUserName(users.getUserName());
        //将密码加密后传入数据库
        users1.setPassword(bCryptPasswordEncoder.encode(users.getPassword()));
        users1.setNickName(users.getNickName());
        users1.setEmail(users.getEmail());
        List<String> roles = new ArrayList<>();
        roles.add("ROLE_USER");
        users1.setRole(roles.get(0));
        //将用户信息存入用户表
        int insert = usersMapper.insert(users1);
        Users result = usersMapper.findByName(users1.getUserName());
        if (result.getUserName()!= null){
            //将用户的角色信息插入user_role
            userRoleMapper.save(users.getUserName(),"ROLE_USER");
            result.setRoles(roles);
            return result;
        }
        return null;
    }

    @Override
    public Users findByNickName(String nickName) {
        return usersMapper.findByNickName(nickName);
    }

    @Override
    public void updatePassword(String userName, String oldPassword, String newPassword) {
        //bc加密后传入数据库,bc无法逆运算，同样的密码生成的code也不一样。
        String bcNewPassword = bCryptPasswordEncoder.encode(newPassword);
        usersMapper.updatePassword(userName,oldPassword,bcNewPassword);
    }

}